﻿using System;
using System.IO;

using Microsoft.AspNetCore.Http;

namespace Hang.Blog.Helper {
    public class FileHelper {

        public static string SaveFile(IFormFile file, string subDir, long idd, string domain) {
            var stream = file.OpenReadStream();
            MemoryStream ms = SttreamHelper.StreamToMemoryStream(stream);
            ms.Position = 0;
            byte[] buffer = new byte[ms.Length];
            ms.Read(buffer, 0, (int)ms.Length);
            var direPath = AppDomain.CurrentDomain.BaseDirectory  + StringConsts.Upload;
            if (!Directory.Exists(direPath)) {
                Directory.CreateDirectory(direPath);
            }
            direPath += "/" + subDir + "/";
            if (!Directory.Exists(direPath)) {
                Directory.CreateDirectory(direPath);
            }
            var desDir = direPath + idd.ToString() + "/";
            if (!Directory.Exists(desDir)) {
                Directory.CreateDirectory(desDir);
            }
            var filePath = Path.Combine(desDir + file.FileName);
            File.WriteAllBytes(filePath, buffer);//写入文件
            return domain + filePath.Replace(AppDomain.CurrentDomain.BaseDirectory, "");
        }
    }
}
